package com.huanuo.internetofthings.service.impact.statistics;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.unicorn.framework.core.ResponseDto;
import org.unicorn.framework.core.exception.PendingException;

import com.google.common.collect.Lists;
import com.huanuo.internetofthings.bo.deviceType.DeviceType;
import com.huanuo.internetofthings.bo.impact.ImpactMonthStatistics;
import com.huanuo.internetofthings.bo.user.UserInfo;
import com.huanuo.internetofthings.dto.impact.ImpactDeviceStatisticsReqDto;
import com.huanuo.internetofthings.dto.statistics.ImpactDeviceStatisticsRes;
import com.huanuo.internetofthings.enums.ImpactDeviceStatisticsType;
import com.huanuo.internetofthings.service.deviceType.DeviceTypeService;
/**
 * 统计用户所在组按设备类型的汇总情况    返回 设备总数、在网总数情况
 * @author xiebin
 *
 */
@Service
public class ImpactDeviceTypeStatisticsService extends AbstractImpactDeviceStatisticsService {
	
	@Autowired
	private DeviceTypeService  deviceTypeService;
    
	@Override
	public ImpactMonthStatistics getImpactMonthStatistics(UserInfo userInfo) throws PendingException {
		ImpactMonthStatistics impactMonthStatistics = new ImpactMonthStatistics();
		impactMonthStatistics.setGroupNo(userInfo.getGroupNo());
		int year = getYear();
		impactMonthStatistics.setYear(year);
		return impactMonthStatistics;
	}

	@Override
	public ResponseDto<?> calculationStatistics(List<ImpactMonthStatistics> impactMonthStatisticsList,UserInfo userInfo)throws PendingException {
		//按设备类型分组
		Map<Integer, List<ImpactMonthStatistics>> groupbyDeviceType = impactMonthStatisticsList.stream()
						.collect(Collectors.groupingBy(ImpactMonthStatistics::getDeviceTypeId));
		Set<Integer>  deviceTypeIdSet=groupbyDeviceType.keySet();
		List<ImpactDeviceStatisticsRes> impactDeviceStatisticsResList = Lists.newArrayList();
		for(Integer deviceTypeId:deviceTypeIdSet){
			ImpactDeviceStatisticsRes impactDeviceStatisticsRes=new ImpactDeviceStatisticsRes();
			DeviceType deviceType=deviceTypeService.selectByPrimaryKey(deviceTypeId);
			impactDeviceStatisticsRes.setDeviceType(deviceType);
			//设备总数
			Integer deviceTotal = groupbyDeviceType.get(deviceTypeId).stream().mapToInt(ImpactMonthStatistics::getDeviceTotal).sum();
			impactDeviceStatisticsRes.setDeviceTotal(deviceTotal);
			//设备在网总数
			Integer deviceOnlineTotal = groupbyDeviceType.get(deviceTypeId).stream().mapToInt(ImpactMonthStatistics::getDeviceOnlineTotal).sum();
			impactDeviceStatisticsRes.setDeviceOnlineTotal(deviceOnlineTotal);
			impactDeviceStatisticsResList.add(impactDeviceStatisticsRes);
		}
		return new ResponseDto<>(impactDeviceStatisticsResList);
	}

	@Override
	public boolean supports(ImpactDeviceStatisticsReqDto s) throws PendingException {
		return ImpactDeviceStatisticsType.DeviceType.equals(s.getImpactDeviceStatisticsType());
		
	}

}